#!/bin/bash
THIS_PATH=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
# 同步容器时区
export TZ=Asia/Shanghai
ln -fs /usr/share/zoneinfo/${TZ} /etc/localtime
dpkg-reconfigure -f noninteractive tzdata
###########################################################
# 编译设置
BUILD_RELEASE=yes   # yes/no
BUILD_PLATFORM=1    # 0:linux-amd64 1:linux-arm64 2:windows-x64
BUILD_COLCON=no     # catkin/colcon 
BUILD_TYPE=0        # 0:ROS 1:non-ROS
BUILD_ROS=noetic    # ROS version
###########################################################
# 设置环境变量
cd $THIS_PATH
export WS_ROOT=$THIS_PATH
export ROS_DISTRO=$BUILD_ROS
echo ">>> Build workspace in ROS environment."
echo "ROS DISTRO: ${ROS_DISTRO}"

# 配置运行环境
source /opt/ros/${ROS_DISTRO}-x64/setup.bash
source $WS_ROOT/environ/envsetup.sh
zbuild_setup $BUILD_PLATFORM $BUILD_RELEASE $BUILD_TYPE
export WS_OUTPUT=$WS_ROOT/ws_output/$ZBUILD_PLATFORM

# 编译及安装目录创建
mkdir -p $WS_OUTPUT
BUILD_PATH=$WS_OUTPUT/build
DEVEL_PATH=$WS_OUTPUT/devel
INSTALL_PATH=$WS_OUTPUT/install
rm -rf $BUILD_PATH $DEVEL_PATH $INSTALL_PATH

# 要编译的Packages:
PACKAGES="scripts third_party appkit foundation zeros "
PACKAGES+="demos ros1_node"

CMAKE_TOOL="-DCMAKE_TOOLCHAIN_FILE=$WS_ROOT/toolchain-aarch64.cmake "
CMAKE_ARGS="-DCMAKE_C_COMPILER_FORCED=ON -DCMAKE_CXX_COMPILER_FORCED=ON \
            -DCMAKE_VERBOSE_MAKEFILE=ON"
# 开始编译
if [ ${BUILD_COLCON} = "yes" ];then
    export WS_ROSBUILD="colcon"
    COLCON_ARGS="--build-base=$BUILD_PATH --install-base=$INSTALL_PATH --merge-install \
        --cmake-force-configure --cmake-args ${CMAKE_TOOL} ${CMAKE_ARGS}"
    colcon build $COLCON_ARGS --packages-select ${PACKAGES}
else
    catkin_make_isolated --build-space $BUILD_PATH --devel-space $DEVEL_PATH \
	    --install-space $INSTALL_PATH --merge --install --pkg ${PACKAGES} --cmake-args ${CMAKE_TOOL}
fi

if [ $? -ne 0 ]; then
    echo "project build error, exit!"
    exit 1
fi

# 目标打包
echo "=============================================================="
cd ${WS_OUTPUT}
rm -rf ${INSTALL_PATH}/include
rm -rf ${INSTALL_PATH}/lib/lib*.a
tar zcf install.tar.gz install
cd ${WS_ROOT}
date
echo "project build success --> install.tar.gz"
echo "=============================================================="
